<?php
/*
 * @Author       : ZengHao
 * @Date         : 2023-12-23 18:38:47
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-02-25 18:34:31
 * @FilePath     : /inc/functions/el-theme.php
 * @Description  : 
 * Copyright 2023 www.exehub.com, All Rights Reserved. 
 * 2023-12-23 18:38:47
 */

/**
 * 主题启动时执行函数，跳转到主题设置页面
 *
 * @return
 */
function el_init_theme()
{
    global $pagenow;
    if ('themes.php' == $pagenow && isset($_GET['activated'])) {
        wp_redirect(admin_url('admin.php?page=eleven_options'));
    }
}
add_action('after_setup_theme', 'el_init_theme');
add_action('after_switch_theme', 'el_init_theme');

// 给文章启用文章缩略图功能
add_theme_support('post-thumbnails', array('post'));
// 给页面启用文章缩略图功能
add_theme_support('post-thumbnails', array('page'));

//开启WordPress链接功能
add_filter('pre_option_link_manager_enabled', '__return_true');

// 加载css和js文件
add_action('wp_enqueue_scripts', 'el_load_scripts');
function el_load_scripts()
{
    if (!is_admin()) {
        // 删除已注册的脚本
        wp_deregister_script('jquery');
        wp_deregister_script('l10n');
        // 主题的自带CSS JS地址
        $purl = EL_ASSETS;

        // 使用CDN的方式，注释CDN的数组
        $cdn_css = array(
            'no' => array(
                'normalize' => 'normalize.min',
                'fontawesome' => 'font-awesome.min',
                'bootstrap' => 'bootstrap.min',
            ), // 不使用CDN
            'staticfile' => array(
                'normalize' => '//cdn.staticfile.org/normalize/8.0.1/normalize.min.css',
                'fontawesome' => '//cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css',
                'bootstrap' => '//cdn.staticfile.org/bootstrap/5.3.1/css/bootstrap.min.css'
            ), // 使用 七牛云-CDN
            'bootcdn' => array(
                'normalize' => '//cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css',
                'fontawesome' => '//cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
                'bootstrap' => '//cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css',
            ), // 使用 bootcdn-CDN
            'cdnjs' => array(
                'normalize' => '//cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css',
                'fontawesome' => '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
                'bootstrap' => '//cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.1/css/bootstrap.min.css',
            ), // 使用 cdnjs.com-CDN
            'original' => array(
                'normalize' => '//unpkg.com/@csstools/normalize.css',
                'fontawesome' => '//cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css',
                'bootstrap' => '//cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css',
            ), // 使用 框架源站-CDN
        );

        $cdn_js = array(
            'no' => array(
                'jquery' => $purl . 'js/jquery.min.js',
                'bootstrap' => $purl . 'js/bootstrap.bundle.min.js',
            ), // 不使用CDN
            'staticfile' => array(
                'jquery' => '//cdn.staticfile.org/jquery/1.9.1/jquery.min.js',
                'bootstrap' => '//cdn.staticfile.org/bootstrap/5.3.1/js/bootstrap.bundle.min.js',
            ), // 使用 七牛云-CDN
            'bootcdn' => array(
                'jquery' => '//cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js',
                'bootstrap' => '//cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js',
            ), // 使用 bootcdn-CDN
            'cdnjs' => array(
                'jquery' => '//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js',
                'bootstrap' => '//cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.1/js/bootstrap.min.js',
            ), // 使用 cdnjs.com-CDN
            'original' => array(
                'jquery'    => '//code.jquery.com/jquery-1.9.1.min.js',
                'bootstrap' => '//cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js',
            ), // 使用 框架源站-CDN
        );

        // 是否使用CDN
        $js_outlink = _opz('js_outlink') ?: 'no';
        _cssloader(array(
            'fontawesome' => isset($cdn_css[$js_outlink]['fontawesome']) ? $cdn_css[$js_outlink]['fontawesome'] : 'font-awesome.min',
            'bootstrap' => isset($cdn_css[$js_outlink]['bootstrap']) ? $cdn_css[$js_outlink]['bootstrap'] : 'bootstrap.min',
            'swiperbundle' => 'swiper-bundle.min',
            'toast' => 'jquery.toast.min',
            'fancybox' => 'jquery.fancybox.min',
            'main' => 'main.min',
        ));
        wp_register_script('jquery', isset($jss[$js_outlink]['jquery']) ? $cdn_js[$js_outlink]['jquery'] : $purl . 'js/jquery.min.js', false, EL_VERSION, false);
        wp_enqueue_script('bootstrap', isset($jss[$js_outlink]['bootstrap']) ? $cdn_js[$js_outlink]['bootstrap'] : $purl . 'js/bootstrap.min.js', array('jquery'), EL_VERSION, true);
        _jsloader(array('loader'));
    }
}

function _cssloader($arr)
{
    foreach ($arr as $key => $item) {
        $href = $item;
        if (strstr($href, '//') === false) {
            $href = EL_ASSETS . 'css/' . $item . '.css';
        }
        wp_enqueue_style('_' . $key, $href, array(), EL_VERSION, 'all');
    }
}

function _jsloader($arr)
{
    foreach ($arr as $item) {
        wp_enqueue_script('_' . $item, EL_ASSETS . 'js/' . $item . '.js', array(), EL_VERSION, true);
    }
}
/**
 * @description: 通过图片链接获取图片ID
 * @param {*}
 * @return {*}
 */
function el_get_image_id($img_url)
{
    $cache_key = md5($img_url);
    // $post_id   = wp_cache_get($cache_key, 'wp_attachment_id', true);
    $post_id   = ECache::get($cache_key, 'wp_attachment_id');

    if ($post_id === false) {
        $attr    = wp_upload_dir();
        $baseurl = preg_replace("/^(https:\/\/|http:\/\/)/", "", $attr['baseurl']) . '/';
        $post_id = '';

        if (stristr($img_url, $baseurl)) {
            $sql_1       = '//' . preg_replace("/^(https:\/\/|http:\/\/)/", "", $img_url);
            $pattern     = "/(.*\/)(.*)(-\d+x\d+\.)(.*)/";
            $replacement = '$1$2.$4';
            $sql_1       = preg_replace($pattern, $replacement, $sql_1);
            $sql_1       = preg_replace("/\?.+/", $replacement, $sql_1);

            if ($sql_1) {
                global $wpdb;
                $db_results = $wpdb->get_results("SELECT id FROM $wpdb->posts WHERE `guid` like '%$sql_1%'");
                if ($db_results) {
                    if (count($db_results) >= 2) {
                        $post_id = '';
                    } else {
                        $post_id = !empty($db_results[0]->id) ? $db_results[0]->id : '';
                    }
                }
            }
        }

        //添加缓存，时间永久
        ECache::set($cache_key, $post_id, 0, 'wp_attachment_id');
    }
    return $post_id;
}
// 获取分类封面图片
function el_get_taxonomy_img_url($term_id = null, $size = 'full', $default = false)
{
    //return '';
    if (!$term_id) {
        $term_id = get_queried_object_id();
    }
    $img   = '';
    $cache = ECache::get($term_id, 'taxonomy_image_' . $size);

    if (false === $cache) {
        $img = get_option('_taxonomy_image_' . $term_id);
        if ($img) {
            if ($size && 'full' != $size) {
                $img_id = el_get_image_id($img);
                if ($img_id) {
                    $img = wp_get_attachment_image_src($img_id, $size);
                    $img = !empty($img[0]) ? $img[0] : '';
                }
            }
            //缓存数据
            if ($img) {
                ECache::set($term_id, $img, 'taxonomy_image_' . $size);
            } else {
                //缓存1天
                ECache::set($term_id, 'noimg', 'taxonomy_image_' . $size, DAY_IN_SECONDS);
            }
        }
    } elseif ('noimg' == $cache) {
        $img = '';
    } else {
        $img = $cache;
    }
    if ($default) {
        return ('' != $img) ? esc_url($img) : esc_url($default);
    } else {
        return esc_url($img);
    }
}

// 获取网站统计信息
function el_get_site_stat()
{
    $stat = array(
        'count_posts'       => 0, //日志总数
        'count_categories'  => 0, //分类总数
        'count_tags'        => 0, //标签总数
        'count_comments'    => 0, //评论总数
        'count_pages'       => 0, //页面总数
        'count_users'       => 0, //用户总数
        'count_links'       => 0, //链接总数
        'last_update'       => '', //最后更新
    );
    global $wpdb;
    $cache = ECache::get('site_stat');
    if (false === $cache) {
        $last = $wpdb->get_results("SELECT MAX(post_modified) AS MAX_m FROM $wpdb->posts WHERE (post_type = 'post' OR post_type = 'page') AND (post_status = 'publish' OR post_status = 'private')");
        $last = date('Y-n-j', strtotime($last[0]->MAX_m));
        $count_posts = wp_count_posts();
        $stat['count_posts'] = $count_posts->publish;
        $stat['count_categories'] = wp_count_terms('category');
        $stat['count_tags'] = wp_count_terms('post_tag');
        $stat['count_comments'] = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments");
        $count_pages = wp_count_posts('page');
        $stat['count_pages'] = $count_pages->publish;
        $result = count_users();
        $stat['count_users'] = $result['total_users'];
        $stat['count_links'] = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->links WHERE link_visible = 'Y'");
        $stat['last_update'] = $last;
        $cache = $stat;
        ECache::set('site_stat', $stat, EL_CACHE, DAY_IN_SECONDS);
    }
    return $cache;
}

// 侧边栏显示判断
function el_is_show_sidebar()
{
    return apply_filters('el_is_show_sidebar', el_is_show_sidebar_filter());
}

function el_is_show_sidebar_filter()
{
    $is = false;
    if (wp_is_mobile()) {
        return false;
    }
    if (is_single() || is_page()) {
        $show_layout = get_post_meta(get_queried_object_id(), 'show_layout', true);
        $sites       = array("sidebar_left", "sidebar_right");
        if (in_array($show_layout, $sites)) {
            return true;
        } elseif ('no_sidebar' == $show_layout) {
            return false;
        }
    }
    if (_opz('sidebar_home_s') && is_home()) {
        return true;
    }
    if (_opz('sidebar_single_s') && is_single()) {
        return true;
    }
    if (_opz('sidebar_page_s', false) && is_page()) {
        return true;
    }
    if (_opz('sidebar_cat_s') && is_category()) {
        return true;
    }
    if (_opz('sidebar_tag_s') && is_tag()) {
        return true;
    }
    if (_opz('sidebar_search_s') && is_search()) {
        return true;
    }

    if (is_page_template('pages/postsnavs.php')) {
        return true;
    }

    if (is_page_template('pages/newposts.php')) {
        return true;
    }
    if (is_page_template('pages/sidebar.php')) {
        return true;
    }
    return $is;
}


function  _bodyclass()
{
    $class = '';
    $class .= el_get_theme_mode() == 'light' ? 'eleven-light' : 'eleven-dark';
    // 增加字体class

    return apply_filters('el_add_bodyclass', trim($class));
}

//主题切换
//TODO:自动切换
function el_get_theme_mode()
{
    $theme_mode = _opz('theme_mode', 'light');
    if (isset($_COOKIE["theme_mode"])) {
        $theme_mode = $_COOKIE["theme_mode"];
    } else {
        $time = current_time('G');
        if ('auto' == $theme_mode) {
            if ($time > 19 || $time < 9) {
                $theme_mode = 'dark';
            } else {
                $theme_mode = 'light';
            }
        }
    }
    return apply_filters('el_theme_mode', $theme_mode);
}

//外链重定向添加路由
function el_add_gophp_query_vars($public_query_vars)
{
    if (!is_admin()) {
        $public_query_vars[] = 'golink'; // 添加参数白名单oauth，代表是各种OAuth登录处理页
    }
    return $public_query_vars;
}
add_filter('query_vars', 'el_add_gophp_query_vars');

function el_gophp_template()
{
    $golink = get_query_var('golink');
    if ($golink) {
        global $wp_query;
        $wp_query->is_home = false;
        $wp_query->is_page = true; //将该模板改为页面属性，而非首页
        $template          = TEMPLATEPATH . '/go.php';
        @session_start();
        $_SESSION['GOLINK'] = $golink;
        load_template($template);
        exit;
    }
}
add_action('template_redirect', 'el_gophp_template', 5);

function el_get_gourl($url)
{
    $url = base64_encode($url);

    return esc_url(home_url('?golink=' . $url));
}

//评论者链接重定向
add_filter('get_comment_author_link', 'add_redirect_comment_link', 5);
add_filter('comment_text', 'add_redirect_comment_link', 99);
function add_redirect_comment_link($text = '')
{
    return go_link($text);
}

function go_link($text = '', $link = false)
{
    if (!$text || !_opz('go_link_s')) {
        return $text;
    }
    if ($link) {
        if (el_is_go_link($text)) {
            $text = el_get_gourl($text);
        }
        return $text;
    }
    preg_match_all("/<a(.*?)href='(.*?)'(.*?)>/", $text, $matches);
    if ($matches) {
        foreach ($matches[2] as $val) {
            if (el_is_go_link($val)) {
                $text = str_replace("href=\"$val\"", "href=\"" . el_get_gourl($val) . "\" ", $text);
            }
        }
        foreach ($matches[1] as $val) {
            $text = str_replace("<a" . $val, "<a" . $val . " target=\"_blank\" ", $text);
        }
    }
    return $text;
}

if (_opz('go_link_s') && _opz('go_link_post')) {
    add_filter('the_content', 'the_content_nofollow', 999);
    function the_content_nofollow($content)
    {
        $pattern = '/<a(.*?)href="(.*?)"(.*?)>/';
        preg_match_all($pattern, $content, $matches);
        if ($matches) {
            foreach ($matches[2] as $val) {
                if (el_is_go_link($val)) {
                    $content = str_replace("href=\"$val\"", "href=\"" . el_get_gourl($val) . "\" ", $content);
                }
            }
        }
        return $content;
    }
}

//外链重定向判断
function el_is_go_link($url)
{

    if (strpos($url, '://') == false) {
        return false;
    }

    if (strpos($url, el_get_url_top_host())) {
        return false;
    }

    $go_link_exclude_domain = _opz('go_link_exclude_domain');
    if ($go_link_exclude_domain) {
        $exclude_domain = preg_split("/,|，|\s|\n/", $go_link_exclude_domain);
        if (in_array(el_get_url_top_host($url), $exclude_domain)) {
            return false;
        }
    }

    return true;
}

//获取顶级域名
function el_get_url_top_host($url = '')
{
    $url   = $url ? $url : home_url();
    $url   = strtolower($url); //首先转成小写
    $hosts = parse_url($url);
    $host  = !empty($hosts['host']) ? $hosts['host'] : $url;
    //查看是几级域名
    $data = explode('.', $host);
    $n    = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if (($n > 2) && preg_match($preg, $host)) {
        //双后缀取后3位
        $host = $data[$n - 3] . '.' . $data[$n - 2] . '.' . $data[$n - 1];
    } elseif (($n > 1)) {
        //非双后缀取后两位
        $host = $data[$n - 2] . '.' . $data[$n - 1];
    }
    return $host;
}

//图片灯箱
if (_opz('imagelightbox',true)) {
    add_filter('the_content', 'imgbox_replace');
    function imgbox_replace($content)
    {
        $pattern     = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|ico|tiff|svg)(\?.*?|)('|\")(.*?)>(.*?)<\/a>/i";
        $replacement = '<a$1href=$2$3.$4$5$6 data-fancybox="gallery"$7>$8</a>';
        $content     = preg_replace($pattern, $replacement, $content);
        return $content;
    }
}

//disable srcset on images
function disable_srcset( $sources ) {
    return false;
    }
    add_filter( 'wp_calculate_image_srcset', 'disable_srcset' );

//文章图片异步加载
if (_opz('lazy_posts_content',false)) {
    add_filter('the_content', 'lazy_img_replace');
    function lazy_img_replace($content)
    {
        $pattern = "/<img(.*?)src=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|ico|tiff|svg|webp)('|\")(.*?)>/i";

        $replacement = '<img$1src="' . EL_ASSETS . '/img/thumbnail-lg.svg' . '" data-src=$2$3.$4$5 $6>';
        $content     = preg_replace($pattern, $replacement, $content);
        $pattern     = "/<img(.*?)srcset=('|\")([^>]*)('|\")(.*?)>/i";
        $replacement = '<img$1data-srcset=$2$3$4 $5>';
        $content     = preg_replace($pattern, $replacement, $content);
        return $content;
    }
}

if (_opz('go_link_s') && _opz('go_link_post')) {
    add_filter('the_content', 'the_content_nofollow', 999);
    function the_content_nofollow($content)
    {
        $pattern = '/<a(.*?)href="(.*?)"(.*?)>/';
        preg_match_all($pattern, $content, $matches);
        if ($matches) {
            foreach ($matches[2] as $val) {
                if (el_is_go_link($val)) {
                    $content = str_replace("href=\"$val\"", "href=\"" . el_get_gourl($val) . "\" ", $content);
                }
            }
        }
        return $content;
    }
}

if (_opz('post_img_auto_alt', false)) {
    add_filter('the_content', 'the_content_img_auto_alt', 999);
    function the_content_img_auto_alt($content)
    {
        global $post;
        $alt = el_page_title();
        //清除为空的alt
        $content = str_replace('alt=""', '', $content);
        preg_match_all('/<img (.*?)\/>/', $content, $images);

        if (!is_null($images)) {
            foreach ($images[1] as $index => $value) {
                preg_match('/alt="(.*?)"/', $value, $is_alt);

                if (empty($is_alt[1])) {
                    //判断没有alt则添加
                    $new_img = str_replace('<img', '<img alt="图片[' . ($index + 1) . ']' . _get_delimiter() . esc_attr(strip_tags($alt)) . '"', $images[0][$index]);
                    $content = str_replace($images[0][$index], $new_img, $content);
                }
            }
        }
        return $content;
    }
}

//图片默认连接到媒体文件(原始链接)
update_option('image_default_link_type', 'file');